package com.srwl.mytx.utils;

import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


public class AESUtil {
    //生成AES秘钥，然后Base64编码
    public final static String ENCODING = "UTF-8";

    public static String genKeyAES() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey key = keyGen.generateKey();
        return byte2Base64(key.getEncoded());
    }

    //将Base64编码后的AES秘钥转换成SecretKey对象
    public static SecretKey loadKeyAES(String base64Key) throws Exception {
         byte[] bytes = base642Byte(base64Key);

        SecretKeySpec key = new SecretKeySpec(bytes, "AES");
        return key;
    }


    //加密
    public static byte[] encryptAES(byte[] source, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(source);
    }

    //解密
    public static byte[] decryptAES(byte[] source, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(source);
    }


    public static String byte2Base64(byte[]bytes) throws UnsupportedEncodingException {

        // 执行编码

        return android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP);

    }


    public static byte[]  base642Byte(String str) throws UnsupportedEncodingException {
        // 执行解码
        return android.util.Base64.decode(str, android.util.Base64.NO_WRAP);
    }

    //需要sdk level 26

//    public static String byte2Base64(byte[] bytes)  {
//
//        java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
//        return encoder.encodeToString(bytes);
//
//    }
//
//
//    public static byte[] base642Byte(String src)  {
//        java.util.Base64.Decoder decoder = java.util.Base64.getDecoder();
//        decoder.decode(src);
//        // 执行解码
//        return decoder.decode(src);
//    }

}
